'use strict'
import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import { getToken, removeToken } from '@/utils/auth'

Vue.use(ElementUI)
axios.interceptors.request.use(config => {
  config.headers['token'] = getToken() // 请求头带上token
  return config
}, error => {
  return Promise.reject(error)
})
axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})
function checkStatus(response) {
  console.log(response)
  // 如果http状态码正常，则直接返回数 据
  if (response && response.status === 401) { // 401, token失效
    removeToken()
    ElementUI.MessageBox.alert('登录异常', '登录异常', {
      confirmButtonText: '确定',
      callback: action => {
        router.push({name: 'login'}, () => {
          location.reload() // 刷新页面, 清空整站临时存储数据
        })
      }
    });
  } else if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}
function getHead(url) {
  const arr = ['login'] // 不需要header 的接口
  if (url.indexOf(...arr) == -1 && getToken()) {
    const val = getToken()
    const header = {
      'Authorization': 'Bearer ' + val
    }
    return header
  }
  return {}
}
function checkCode(res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status === -404) {
    return
    // alert(res.msg)
  }
  return res
}
// export default service
export default {
  exportRate(downUrl, data) {
    return axios({
      url: downUrl,
      method: 'get',
      headers: Object.assign(getHead(downUrl), { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }),
      params: data,
      responseType: 'blob' // 二进制流
    })
  },
  post(url, data) {
    return axios({
      method: 'post',
      url,
      data: data,
      timeout: 10000,
      headers: Object.assign(getHead(url), { 'Content-Type': 'application/json; charset=UTF-8' })
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },

  get(url, params) {
    return axios({
      method: 'get',
      url,
      params: params, // get 请求时带的参数
      timeout: 10000,
      headers: Object.assign(getHead(url), { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' })
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },

}
